<?php

namespace app\api\controller;

use app\admin\model\ContactService;
use app\admin\model\GiftList;
use app\admin\model\Goods;
use app\admin\model\MiningCoin;
use app\admin\model\MiningUserWallet;
use app\admin\model\MiningWithdraw;
use app\admin\model\UserLevel;
use app\admin\model\UserLevelRule;
use app\admin\model\UserLevelBzz;
use app\admin\model\UserLevelRuleBzz;
use app\admin\model\UserMiner;
use app\admin\model\WaterLock;
use app\admin\model\WaterMining;
use app\admin\model\WaterPledge;
use app\common\controller\Api;
use app\common\model\Config;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['index','goodsList'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $data = curl_get("https://api.filscout.com/api/v1/network/overview/info");
        $data = json_decode($data,true);
//        $return_data['first'] = $data['data']['statistic']['tipset_height'];
        $return_data['two'] = round($data['data']['totalPower'] * 1024,2);
//        $data['two'] = round($data['data']['statistic']['power']['power_in_bytes'] / 1024 / 1024 /1024 /1024 /1024 / 1024,2);
        $return_data['three'] = $data['data']['activeMiners'];

        $height = curl_get("https://api.filscout.com/api/v1/network/overview/height");
        $data = json_decode($height,true);
        $return_data['first'] = $data['data']['tipSetHeight'];
        $this->success('ok',$return_data);
//        $this->success('请求成功');
    }

    /**
     * 商品列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsList()
    {
        //TODO 接口没写
        $data = Goods::where('status',1)->order('sort','desc')->select();

        $this->success('ok',$data);
    }

    /**
     * 联系客服
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function serviceList()
    {
        $list = ContactService::field('name,type,account')->where('status',1)->select();

        $this->success('ok',$list);
    }

    //订单购买
    public function order()
    {
        if (empty($this->request->post())) {
            $id = $this->request->get('id');
            $goods_data = Goods::where('id',$id)->find();
            $this->success('ok',$goods_data);
        }
        $id = $this->request->post('id');
        $number = round($this->request->post('number'),1);

        $goods_data = Goods::where('status',1)->where('id',$id)->find();
        if (empty($goods_data)) {
            $this->error('找不到该商品！');
        }

        if ($number < $goods_data->lowest) {
            $this->error('最少购买'.$goods_data->lowest);
        }
        $mining_coin_str = $goods_data->mining_coin_str;
        $coin_id = MiningCoin::where('coin_type',$mining_coin_str)->value('id');
        $user_id =  $this->auth->getUser()->id;
        $user_usdt_balance = MiningUserWallet::where('user_id',$user_id)->where('mining_coin_id',$coin_id)->value('balance');
        $usdt_amount = $number * $goods_data->price;
        if ($user_usdt_balance < $usdt_amount) {
            $this->error($mining_coin_str."余额不足，请充值！");
        }


        //        $user_fil_balance = MiningUserWallet::where('user_id',$user_id)->where('mining_coin_id',COIN2_ID)->value('balance');
        //        $fil_amount = $number * $goods_data->t_fil;
        //        if ($user_fil_balance < $fil_amount) {
        //            $this->error("FIL余额不够，需要{$fil_amount}FIL，现在有{$user_fil_balance}FIL");
        //        }

        $t_fil = Config::where('name','t_fil')->value('value');
        $t_gas = Config::where('name','t_gas')->value('value');
        $day_balance = $goods_data->begin_day;
        $start_time = date("Y-m-d",strtotime('+1 day'));
        $end_time = date("Y-m-d",strtotime('+'.($goods_data->duration).' day'));
        if ($goods_data->type == 1) {
            $balance_number = $number;
        } else if ($goods_data->type ==2){
            $balance_number = 0;
        } else if ($goods_data->type == 3) {
            $user_balance = GiftList::where('user_id',$this->auth->getUser()->id)->where('status',0)->sum('balance');

            if ($user_balance < $number) {
                    $this->error('对不起,赠送的矿机你最多只可以购买：'.$user_balance);
            }
            $balance_number = $number;
            $day_balance = 0;
            $start_time = date("Y-m-d", strtotime("+".$goods_data->begin_day." day"));
        }
        if ($goods_data->type == 3) {
            $tmp_number= $number;
            $gift_list = GiftList::where('user_id',$this->auth->getUser()->id)->where('status',0)->select();
            foreach ($gift_list as $value) {
                if ($tmp_number <= 0 ) {
                    break;
                }
                if ($tmp_number >= $value->balance) {
                    GiftList::where('id',$value->id)->update(['balance' =>0,'status'=>1]);
                    $tmp_number = $tmp_number - $value->balance;
                } else {
                    GiftList::where('id',$value->id)->update(['balance' =>$value->balance - $tmp_number]);
                    $tmp_number = 0;
                }
            }
        }

        $user_miner = UserMiner::create([
            'order_no' => generate_order_number(),
            'name' => $goods_data->name,
            'user_id' => $this->auth->getUser()->id,
            'goods_id' => $goods_data->id,
            'image' => $goods_data->image,
            'number' => $number,
            'balance_number' => $balance_number,
            'max_pledge' => $t_fil * $number,
            'pledge' => 0,
            //'gift_pledge' => $fil_amount,
            'gift_pledge' => 0,
            'gas' => 0,
            'max_gas' => $t_gas * $number,
            'day' => $goods_data->begin_day,
            'day_balance' => $day_balance,
            'mining_coin_str' => $mining_coin_str,
            'price' => $goods_data->price,
            'money' => $usdt_amount,
            'begin_day' => $goods_data->begin_day,
            'duration' => $goods_data->duration,
            'direct_push' => $goods_data->direct_push,
            'second_push' => $goods_data->second_push,
            'service_rate' => $goods_data->service_rate,
            'lock_rate' => $goods_data->lock_rate,
            'type' => $goods_data->type,
            'ktype' => $goods_data->ktype,
            'start_time' => $start_time,
            'end_time' => $end_time
        ]);

        if($goods_data->ktype == 2 && $user_miner !== false){
             
            $begin_day = $goods_data->begin_day;

            if($begin_day <= 0){
                $begin_day = 1;
            }

            for ($i=0; $i < $number; $i++) { 
        
                $log = array();
                $log['user_id'] = $this->auth->getUser()->id;
                $log['user_miner_id'] = $user_miner->id;
                $log['num'] = 1;
                $log['start_time'] = date("Y-m-d",strtotime('+'.($begin_day).' day'));
                $log['end_time'] = date("Y-m-d",strtotime('+'.($begin_day + 30).' day'));
                $log['create_time'] = date('Y-m-d H:i:s',time());

                Db::name("user_miner_ex_bzz")->insert($log);
            }
        }

        MiningUserWallet::where('user_id',$user_id)->where('mining_coin_id',$coin_id)->setDec('balance',$usdt_amount);
        //MiningUserWallet::where('user_id',$user_id)->where('mining_coin_id',COIN2_ID)->setDec('balance',$fil_amount);
        WaterMining::create([
            'detail_id' => $user_miner->id,
            //'relate_user_id' => $to_user->id,
            'user_id' => $user_id,
            'type' => MINING_WATER_BUY,
            'ktype' => $goods_data->ktype,
            'coin_type' => $mining_coin_str,
            'money' => $usdt_amount,
            'balance' => $user_usdt_balance - $usdt_amount
        ]);

        //        if (!empty($fil_amount)) {
        //            WaterMining::create([
        //                'detail_id' => $user_miner->id,
        ////            'relate_user_id' => $to_user->id,
        //                'user_id' => $user_id,
        //                'type' => MINING_WATER_PLEDGE,
        //                'coin_type' => COIN2,
        //                'money' => $fil_amount,
        //                'balance' => $user_fil_balance - $fil_amount
        //            ]);
        //        }

        if($goods_data->ktype == 1){

            //邀请收益
            $user_level = UserLevel::order('id','desc')->select();
            $parents_ids = getParents($user_id,'id,level');

            //分红
            $level = 0;
            $equal_level = 0;
            $tmp_level_rate = 0;
            foreach ($parents_ids as $key => $parent) {
                $level_info = UserLevelRule::where('user_level_id',$parent->level)->find();
                $exist = UserMiner::where('user_id',$parent->id)->find();
                if ($key == 0 && (!empty($exist) || !empty($level_info) )) {    //直推
                    //$level_info_direct_push_rate = $level_info->direct_push_rate ?? 0;
                    $direct_profit = round($goods_data->price * $number * $goods_data->direct_push / 100, 4);
                    //$level_direct_profit = round($level_info_direct_push_rate * $number * $goods_data->price / 100,4);
                    //$direct_profit = $level_direct_profit + $direct_profit;
                    //$direct_profit = round($level_info->direct_push_rate * $usdt_amount / 100,2);
                    if (!empty($direct_profit)) {
                        $balance = MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                            ->value('balance');
                        MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                            ->setInc('balance',$direct_profit);
                        WaterMining::create([
                            'detail_id' => $user_miner->id,
                            'user_id' => $parent->id,
                            'type' => MINING_WATER_DIRECT_PUSH,
                            'ktype' => $goods_data->ktype,
                            'coin_type' => $mining_coin_str,
                            'money' => $direct_profit,
                            'balance' => $balance + $direct_profit
                        ]);
                    }
                } elseif ($key == 1 && (!empty($exist) || !empty($level_info) )) {      //间推
                    //$level_info_second_push_rate = $level_info->second_push_rate ?? 0;
                    $second_profit = round($goods_data->price * $number * $goods_data->second_push / 100,4);
                    //$level_second_profit = round($level_info_second_push_rate * $number * $goods_data->price / 100,4);
                    //$second_profit =   $second_profit;
                    //$second_profit = round($level_info->second_push_rate * $usdt_amount / 100,2);
                    if (!empty($second_profit)) {
                        $balance = MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                            ->value('balance');
                        MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                            ->setInc('balance',$second_profit);
                        WaterMining::create([
                            'detail_id' => $user_miner->id,
                            'user_id' => $parent->id,
                            'type' => MINING_WATER_SECOND_PUSH,
                            'ktype' => $goods_data->ktype,
                            'coin_type' => $mining_coin_str,
                            'money' => $second_profit,
                            'balance' => $balance + $second_profit
                        ]);
                    }
                }

                //社区
                if (!empty($goods_data->team)) {
                    if ($parent->level > $level &&
                        !empty($level_info->team_rate)
                    ) {
                        $team_profit = round(($level_info->team_rate - $tmp_level_rate) * $number * $goods_data->price / 100,4);
                        if (!empty($team_profit)) {
                            $balance = MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                                ->value('balance');
                            MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                                ->setInc('balance',$team_profit);
                            WaterMining::create([
                                'detail_id' => $user_miner->id,
                                'user_id' => $parent->id,
                                'type' => MINING_WATER_TEAM,
                                'ktype' => $goods_data->ktype,
                                'coin_type' => $mining_coin_str,
                                'money' => $team_profit,
                                'balance' => $balance + $team_profit
                            ]);
                            $level = $level_info->id;
                            $tmp_level_rate = $level_info->team_rate;
                        }
                    //$team_profit = round(($level_info->team_rate - $tmp_level_rate) * $usdt_amount / 100,2);

                        //平级
                    }
                }


                //            elseif ($parent->level == $level &&
                //                !empty($level_info->equal_rate) &&
                //                $parent->level > $equal_level
                //            ) {
                //                $equal_profit = round($level_info->equal_rate * $number ,4 );
                ////                $equal_profit = round($level_info->equal_rate * $usdt_amount / 100,2);
                //                $balance = MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',COIN1_ID)
                //                    ->value('balance');
                //                MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',COIN1_ID)
                //                    ->setInc('balance',$equal_profit);
                //                WaterMining::create([
                //                    'detail_id' => $user_miner->id,
                //                    'user_id' => $parent->id,
                //                    'type' => MINING_WATER_TEAM_EQUAL,
                //                    'ktype' => $goods_data->ktype,
                //                    'coin_type' => COIN1,
                //                    'money' => $equal_profit,
                //                    'balance' => $balance + $equal_profit
                //                ]);
                //                $equal_level = $level_info->id;
                //            }
            }

            $parents_ids[] = \app\common\model\User::field('id,level')->where('id',$this->auth->getUser()->id)->find();
           //制度升级
            foreach ($parents_ids as $parent) {
                $child_ids = getChildsIds($parent->id);
                $team_buy = UserMiner::whereIn('user_id',$child_ids)->sum('number');
                $direct_push = \app\common\model\User::where('pid',$parent->id)->count();
                $buy = UserMiner::where('user_id',$parent->id)->sum('number');
                foreach ($user_level as $userlevel) {
                    if ($parent->level >= $userlevel->id
                    ) {
                        break;
                    }
                    if ($direct_push < $userlevel->direct_push ||
                        $buy < $userlevel->buy ||
                        $team_buy < $userlevel->team_profit
                    ) {
                        continue;
                    }

                    \app\common\model\User::where('id',$parent->id)->update(['level' => $userlevel->id]);
                    break;
                }
            }
        }

        if($goods_data->ktype == 2){
            
            //邀请收益
            $user_level = UserLevelBzz::order('id','desc')->select();
            $parents_ids = getParents($user_id,'id,level_bzz');

            //分红
            $level = 0;
            $equal_level = 0;
            $tmp_level_rate = 0;
            foreach ($parents_ids as $key => $parent) {
                $level_info = UserLevelRuleBzz::where('user_level_id',$parent->level_bzz)->find();
                $exist = UserMiner::where('user_id',$parent->id)->find();
                if ($key == 0 && (!empty($exist) || !empty($level_info) )) {    //直推
                    //$level_info_direct_push_rate = $level_info->direct_push_rate ?? 0;
                    $direct_profit = round($goods_data->price * $number * $goods_data->direct_push / 100, 4);
                    //$level_direct_profit = round($level_info_direct_push_rate * $number * $goods_data->price / 100,4);
                    //$direct_profit = $level_direct_profit + $direct_profit;
                    //$direct_profit = round($level_info->direct_push_rate * $usdt_amount / 100,2);
                    if (!empty($direct_profit)) {
                        $balance = MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                            ->value('balance');
                        MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                            ->setInc('balance',$direct_profit);
                        WaterMining::create([
                            'detail_id' => $user_miner->id,
                            'user_id' => $parent->id,
                            'type' => MINING_WATER_DIRECT_PUSH,
                            'ktype' => $goods_data->ktype,
                            'coin_type' => $mining_coin_str,
                            'money' => $direct_profit,
                            'balance' => $balance + $direct_profit
                        ]);
                    }
                } elseif ($key == 1 && (!empty($exist) || !empty($level_info) )) {      //间推
                    //$level_info_second_push_rate = $level_info->second_push_rate ?? 0;
                    $second_profit = round($goods_data->price * $number * $goods_data->second_push / 100,4);
                    //$level_second_profit = round($level_info_second_push_rate * $number * $goods_data->price / 100,4);
                    //$second_profit =   $second_profit;
                    //$second_profit = round($level_info->second_push_rate * $usdt_amount / 100,2);
                    if (!empty($second_profit)) {
                        $balance = MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                            ->value('balance');
                        MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                            ->setInc('balance',$second_profit);
                        WaterMining::create([
                            'detail_id' => $user_miner->id,
                            'user_id' => $parent->id,
                            'type' => MINING_WATER_SECOND_PUSH,
                            'ktype' => $goods_data->ktype,
                            'coin_type' => $mining_coin_str,
                            'money' => $second_profit,
                            'balance' => $balance + $second_profit
                        ]);
                    }
                }

                //社区
                if (!empty($goods_data->team)) {
                    if ($parent->level_bzz > $level && !empty($level_info->team_rate)) {
                        $team_profit = round(($level_info->team_rate - $tmp_level_rate) * $number * $goods_data->price / 100,4);
                        if (!empty($team_profit)) {
                            $balance = MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                                ->value('balance');
                            MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',$coin_id)
                                ->setInc('balance',$team_profit);
                            WaterMining::create([
                                'detail_id' => $user_miner->id,
                                'user_id' => $parent->id,
                                'type' => MINING_WATER_TEAM,
                                'ktype' => $goods_data->ktype,
                                'coin_type' => $mining_coin_str,
                                'money' => $team_profit,
                                'balance' => $balance + $team_profit
                            ]);
                            $level = $level_info->id;
                            $tmp_level_rate = $level_info->team_rate;
                        }
                    //$team_profit = round(($level_info->team_rate - $tmp_level_rate) * $usdt_amount / 100,2);

                        //平级
                    }
                }


                //            elseif ($parent->level_bzz == $level &&
                //                !empty($level_info->equal_rate) &&
                //                $parent->level_bzz > $equal_level
                //            ) {
                //                $equal_profit = round($level_info->equal_rate * $number ,4 );
                ////                $equal_profit = round($level_info->equal_rate * $usdt_amount / 100,2);
                //                $balance = MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',COIN1_ID)
                //                    ->value('balance');
                //                MiningUserWallet::where('user_id',$parent->id)->where('mining_coin_id',COIN1_ID)
                //                    ->setInc('balance',$equal_profit);
                //                WaterMining::create([
                //                    'detail_id' => $user_miner->id,
                //                    'user_id' => $parent->id,
                //                    'type' => MINING_WATER_TEAM_EQUAL,
                //                    'ktype' => $goods_data->ktype,
                //                    'coin_type' => COIN1,
                //                    'money' => $equal_profit,
                //                    'balance' => $balance + $equal_profit
                //                ]);
                //                $equal_level = $level_info->id;
                //            }
            }

            $parents_ids[] = \app\common\model\User::field('id,level_bzz')->where('id',$this->auth->getUser()->id)->find();
            //制度升级
            foreach ($parents_ids as $parent) {
                $child_ids = getChildsIds($parent->id);
                $team_buy = UserMiner::whereIn('user_id',$child_ids)->sum('number');
                $direct_push = \app\common\model\User::where('pid',$parent->id)->count();
                $buy = UserMiner::where('user_id',$parent->id)->sum('number');
                foreach ($user_level as $userlevel) {
                    if ($parent->level_bzz >= $userlevel->id
                    ) {
                        break;
                    }
                    if ($direct_push < $userlevel->direct_push ||
                        $buy < $userlevel->buy ||
                        $team_buy < $userlevel->team_profit
                    ) {
                        continue;
                    }

                    \app\common\model\User::where('id',$parent->id)->update(['level_bzz' => $userlevel->id]);
                    break;
                }
            }
        }
        $this->success('购买成功！');
    }



    public function coinList()
    {
        $user_id = $this->auth->getUser()->id;
        $data['usdt']['balance'] = MiningUserWallet::where('user_id',$user_id)
            ->where('mining_coin_id',COIN1_ID)->value('balance');
        $data['usdt']['freeze'] = number_format(MiningWithdraw::where('user_id',$this->auth->getUser()->id)->where('mining_coin_id',COIN1_ID)->where('status',0)->sum('number'),4,".","");
        $data['usdt']['total'] = rounddown(MiningUserWallet::where('user_id',$user_id)
            ->where('mining_coin_id',COIN1_ID)->value('balance'),4);

        // $data['bzz']['balance'] = MiningUserWallet::where('user_id',$user_id)
        //     ->where('mining_coin_id',COIN3_ID)->value('balance');
        // $data['bzz']['freeze'] = number_format(MiningWithdraw::where('user_id',$this->auth->getUser()->id)->where('mining_coin_id',COIN3_ID)->where('status',0)->sum('number'),4,".","");
        // $data['bzz']['total'] = rounddown(MiningUserWallet::where('user_id',$user_id)
        //     ->where('mining_coin_id',COIN3_ID)->value('balance'),4);

        $fil_balance = MiningUserWallet::where('user_id',$user_id)
            ->where('mining_coin_id',COIN2_ID)->value('balance');
        $data['fil']['total'] = $fil_balance;
        $data['fil']['balance'] = $fil_balance;
        $data['fil']['cal'] = number_format(WaterMining::whereIn('type',[MINING_WATER_REDUCE,MINING_WATER_MINING,MINING_WATER_LOCK_RELEASE])
            ->where('user_id',$this->auth->getUser()->id)->where('coin_type','FIL')->sum('money'),4,".","");
        $data['fil']['lock'] = $this->auth->getUser()->locks;
        $data['fil']['pledge'] = number_format(UserMiner::where('user_id',$this->auth->getUser()->id)
            ->where('status','<>',2)->sum('pledge') - UserMiner::where('user_id',$this->auth->getUser()->id)
                ->where('status','<>',2)->sum('gift_pledge'),4,".","");

        $fil_balance1 = MiningUserWallet::where('user_id',$user_id)
            ->where('mining_coin_id',COIN3_ID)->value('balance');
        $data['bzz']['total'] = $fil_balance1;
        $data['bzz']['balance'] = $fil_balance1;
        $data['bzz']['cal'] = number_format(WaterMining::whereIn('type',[MINING_WATER_REDUCE,MINING_WATER_MINING,MINING_WATER_LOCK_RELEASE])
            ->where('user_id',$this->auth->getUser()->id)->where('coin_type','BZZ')->sum('money'),4,".","");

        $this->success('ok',$data);
    }


    //我的订单
    public function orderLst()
    {
        $status = $this->request->get('status');
        $status = $status - 1;
        $data = UserMiner::where('user_id',$this->auth->getUser()->id)->order('id','desc')->where('status',$status)->where('ktype','<>',4)->select();//过滤宽带
        foreach ($data as $value) {
            $value->use = $value->balance_number;
//            $value->use = round($value->number * $value->pledge / $value->max_pledge,4);
            $value->not_use = $value->number - $value->balance_number;
//            round($value->number * ($value->max_pledge - $value->pledge) / $value->max_pledge,4);
            $value->pledge = $value->pledge - $value->gift_pledge;

//            $value->pledge = $value->number * $value->pledge / $value->max_pledge;
//            $value->max_pledge = round($value->number * ($value->max_pledge - $value->pledge) / $value->max_pledge,2);

            if($value->ktype == 2){

                $time = date('Y-m-d H:i:s',time());
                //查询矿机使用情况
                $shiyon = Db::name("user_miner_ex_bzz")->where('user_miner_id',$value->id)->where('end_time','>',$time)->count('id');
                $value->shiyon = $shiyon;

                //查询最近到期
                $zuijin = Db::name("user_miner_ex_bzz")->where('user_miner_id',$value->id)->where('end_time','>',$time)->order('end_time','asc')->field('end_time,id,start_time')->select();
                
                if(!empty($zuijin)){

                    foreach($zuijin as $k => $v){
                        $zuijin[$k]['start_time'] = date('Y-m-d',strtotime($v['start_time']));
                        $zuijin[$k]['end_time'] = date('Y-m-d',strtotime($v['end_time']));
                    }

                    $value->zuijin = $zuijin[0]['end_time'];
                    $value->detail = $zuijin;
                }else{
                    $value->zuijin = '';
                    $value->detail = '';
                }
            }else{
                $value->shiyon = 0;
                $value->zuijin = '';
                $value->detail = '';
            }
        }

        //number:数量；price：价格；end_time：结束时间
        $this->success('ok',$data);
    }

    /**
     * 质押
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function pledge()
    {
        if (empty($this->request->post())) {
            $id = $this->request->get('id');
            $data = UserMiner::where('id', $id)->where('user_id',$this->auth->getUser()->id)->whereIn('status',[0,1])->find();
            if (empty($data)) {
                $this->error('找不到该订单');
            }

            $this->success('ok',$data);
        }

        $user_id = $this->auth->getUser()->id;
        $id = $this->request->post('id');
        $number = $this->request->post('number');

        $data = UserMiner::where('id',$id)->where('user_id',$user_id)->whereIn('status',[0,1])->find();
        if (empty($data)) {
            $this->error('找不到该订单');
        }

        if ($data->pledge == $data->max_pledge) {
            $this->error('你已达到最大质押！');
        }


        $total = round($data->max_pledge - $data->gift_pledge + $data->max_gas,4);
        $pledge_num = round($number * ($data->max_pledge - $data->gift_pledge) / $total,4);
        $gas_num = round($number * $data->max_gas / $total,4);

        if ($pledge_num + $data->pledge > $data->max_pledge) {
            $this->error('最大质押：'.$data->max_pledge.',你还可以质押：'. ($data->max_pledge - $data->pledge));
        }

        $user_fil_balance = MiningUserWallet::where('user_id',$user_id)->where('mining_coin_id',COIN2_ID)->value('balance');
        if ($user_fil_balance < $pledge_num) {
            $this->error("质押FIL不够，需要{$number}FIL，现在有{$user_fil_balance}FIL");
        }
        MiningUserWallet::where('user_id',$user_id)
            ->where('mining_coin_id',COIN2_ID)->setDec('balance',$pledge_num);
        WaterMining::create([
            'detail_id' => $data->id,
//            'relate_user_id' => $to_user->id,
            'user_id' => $user_id,
            'type' => MINING_WATER_PLEDGE,
            'coin_type' => COIN2,
            'money' => "-".$pledge_num,
            'balance' => $user_fil_balance - $pledge_num
        ]);

        $pledge_balance = UserMiner::where('user_id',$this->auth->getUser()->id)->whereIn('status',[0,1])->sum('pledge');
        WaterPledge::create([
            'detail_id' => $data->id,
//            'relate_user_id' => $to_user->id,
            'user_id' => $user_id,
            'type' => WATER_PLEDGE_PLEDGE,
            'money' => $pledge_num,
            'balance' => $pledge_balance + $pledge_num
        ]);

        //GAS
        $user_fil_balance = MiningUserWallet::where('user_id',$user_id)->where('mining_coin_id',COIN2_ID)->value('balance');
        MiningUserWallet::where('user_id',$user_id)
            ->where('mining_coin_id',COIN2_ID)->setDec('balance',$gas_num);
        WaterMining::create([
            'detail_id' => $data->id,
//            'relate_user_id' => $to_user->id,
            'user_id' => $user_id,
            'type' => MINING_WATER_PLEDGE_GAS,
            'coin_type' => COIN2,
            'money' => "-".$gas_num,
            'balance' => $user_fil_balance - $gas_num
        ]);

//        WaterPledge::create([
//            'user_id' => $user_id,
//            'money' => "-".$profit_gas_list[$user_id],
//            'balance' => $pledge_balance,
//            'address' => $water_address_name,
//            'type' => WATER_PLEDGE_GAS,
//        ]);

        UserMiner::where('id',$id)->setInc('pledge',$pledge_num);

        $this->success('质押成功');
    }

    public function waterLock()
    {
        $this->loadadminlang('mining/water_lock');
        $page = $this->request->get('page') ?? 1;

        $data = WaterLock::where('user_id',$this->auth->getUser()->id)
            ->order('id','desc')
            ->page($page,30)->select();

        $this->success('ok',$data);
    }

    public function waterPledge()
    {
        $this->loadadminlang('mining/water_pledge');
        $page = $this->request->get('page') ?? 1;

        $data = WaterPledge::where('user_id',$this->auth->getUser()->id)
            ->order('id','desc')
            ->page($page,30)->select();

        $this->success('ok',$data);
    }
}
